<?php 
	require_once('../params.inc');
	require_once('../db.inc');
	require_once('../controls.inc');
	require_once('../utils.inc');
	require_once('sf.inc');
	
	$catname = $par->get('name');
	
	$where = array();
	if ($par->exist('keys')) 
	{
		$keys = new DecodedFieldValues( $par->get('keys') );
		$where = $keys->asArray();
	}
	
	$path = array(
		array('Главная','index.php'),
		isset($keys) ? 'Добавление' : 'Редактирование'
	);
	
	require_once('header.inc');

	$target = new Url($par->get('target'));
	if ($par->exist('keys')) 		//send back id's of changed records
	{		
		$target->setParam('keys', $par->get('keys'));
	}
	
	$dataMgr = new DataManager($catname);
	$fmgr = new Files($catname);
		
	if ($par->exist('del')) 
	{
		$dataMgr->delete( $where );
		
		$fInfo = new Fields($catname);
		$fInfo->open();
		while ($fInfo->fetch()) 
		{
			if ($fInfo->type() == FIELD_TYPE_FILE) 
			{
				$fmgr->del($fInfo->name(), $where, '../../');
			}
		}
	}
	else 
	{
		$fields = array();
		foreach ($par->asArray() as $nm => $val) 
		{
			if ($nm != 'keys' && $nm != 'name' && $nm != 'target') 
			{
				$fields[decFieldName($nm)] = $val;
			}
		}
		
		if (count($where)) 
		{
			$dataMgr->update($fields, $where);
		}		
		else 
		{
			$dataMgr->insert($fields);
			$target->setParam('lastInsertId', $db->lastInsertId());	//send back lastInsertId (if any)
		}

		$fmgr->upload($where);
	}
	
	if (!$dataMgr->isSuccess()) 
	{
		"<br><br>Произошла ошибка, операция не была выполнена<br><br>";
	}
	
	echo "<br><br><button onclick=\"go('" . $target->__toString() ."')\">Продолжить &gt;&gt;</button><br><br><br>";
?>

<br>
<br>
<textarea cols=50 rows=5 style="color:graytext;font-size:8pt" readonly>
<?php echo $dataMgr->getLastRunSQL(); ?>
</textarea>

<script lang=javascript>
<?php
	if ($dataMgr->isSuccess()) 
	{
		echo "go('" . $target->__toString() . "');";
	}
?>
</script>

<?php require_once('footer.inc'); ?>
